package testenv.dao.hibernateimpl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import testenv.dao.ChildDao;
import testenv.model.entity.Child;


@Repository
public class ChildDaoImpl implements ChildDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	
	@Override
	public void deleteChild(Integer childId) {
		Session session = sessionFactory.getCurrentSession();
		Child child = (Child)session.get(Child.class, childId);
		child.getParent().getChildSet().remove(child);
		session.delete(child);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Integer getChildCount() {
		Session session = sessionFactory.getCurrentSession();
		
		Criteria criteria = session.createCriteria(Child.class);
		criteria.setProjection(Projections.rowCount());
		criteria.setCacheable(true);
		
		Integer rowCount = 0;
		List<Integer> result = criteria.list();
		if (!result.isEmpty()) {
			rowCount = result.get(0);
			System.out.println("Total records: " + rowCount);
		}
		
		return rowCount;
	}
	
	
	@Override
	@SuppressWarnings("unchecked")
	public void selectChild() {
		Session session = sessionFactory.getCurrentSession();
		SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM Child;");
		List<Object> resultList = sqlQuery.list();
		
		for (Object result : resultList) {
			System.out.println(result);
		}
	}
	
}
